package org.cuijq.thinking.in.spring.dependency.lookup;

import org.cuijq.thinking.in.spring.ioc.domain.User;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;

/**
 * @Classname ObjectProvider
 * @Description 通过这个类进行依赖查找
 * @Date 2021/4/30 9:58
 * @Created by CuiJQ
 */
public class ObjectProviderDemo {

  public static void main(String[] args) {
    AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext();
    ac.register(ObjectProviderDemo.class);
    ac.refresh();
    lookupByObejctProder(ac);
    lookupifAvaiable(ac);
    lookupByStreamOps(ac);
    ac.close();
  }

  private static void lookupByStreamOps(AnnotationConfigApplicationContext ac) {
    ObjectProvider<String> objectProvider = ac.getBeanProvider(String.class);
//    Iterable<String> stringIterable = objectProvider;
//    for (String string : stringIterable) {
//      System.out.println(string);
//    }

    objectProvider.stream().forEach(System.out::println);
  }

  private static void lookupifAvaiable(AnnotationConfigApplicationContext ac) {
    ObjectProvider<User> userObjectProvider = ac.getBeanProvider(User.class);
    User user = userObjectProvider.getIfAvailable(User::createUser);
    System.out.println("当前user对象" + user);
  }

  @Bean
  @Primary
  public String helloWorld() {
    return "Hello,World";
  }

  @Bean
  public String message() {
    return "Message";
  }

  private static void lookupByObejctProder(AnnotationConfigApplicationContext ac) {
    ObjectProvider<String> objectProvider = ac.getBeanProvider(String.class);
    System.out.println(objectProvider.getObject());
  }
}
